package org.opensource.webflux.socket;

import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import org.springframework.web.reactive.socket.client.WebSocketClient;
import reactor.core.publisher.Flux;

import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class WebsocketClient {
    public static void main(final String[] args) {
        List<Thread> list = new ArrayList<>();
        final WebSocketClient client = new ReactorNettyWebSocketClient();
        for(int i=0; i< 500; i++) {
            int finalI = i;
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    client.execute(URI.create("ws://localhost:8080/echo"), session ->
                            session.send(Flux.just(session.textMessage(new String(String.valueOf(finalI)))))
                                    .thenMany(session.receive().take(1).map(WebSocketMessage::getPayloadAsText))
                                    .doOnNext(System.out::println)
                                    .then())
                            .block(Duration.ofMillis(60000));
                }
            });
            list.add(thread);
            thread.start();
        }
        list.stream().forEach(it -> {
            try {
                it.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
